package com.jxtc.enterprise.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.jxtc.enterprise.common.vo.MiniAppSessoinVO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class WxUtils {


    public static MiniAppSessoinVO code2Session(String code) {
        // todo 将 appid和secret 加密保存在配置文件中，程序运行时再进行解密
        // String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx3b5031cdda30712f&secret=a1d70a342b9ed3efb2a1210607476dea&js_code=" + code + "&grant_type=authorization_code";
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxcdff2287ac2c9afa&secret=7eec4ba25ea40c38e7b74ff4944211c3&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);

        if (responseEntity !=null && responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            MiniAppSessoinVO sessoinEntity = JSONObject.parseObject(sessionData, MiniAppSessoinVO.class);
            return sessoinEntity;
        } else {
            return null;
        }
    }
}
